package org.common.util;

import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

public class SFile {
	public static String DEF_CHARSET="UTF-8";
	
	
	/**
	 * 读取url信息
	 * @param url
	 * @return
	 */
	public static String readUrl(String url){
		try {
			URL urlObject = new URL(url);
			URLConnection urlConn = urlObject.openConnection(); 
			return I2S(urlConn.getInputStream());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return null;
	}
	public  static void rollPath(File path,String innerRootPath,PrintWriter pw){
		String n=path.getName();
		String p=innerRootPath+"/"+n;
		if(path.isFile()){
			pw.println("<li><span ><a onclick=\"showFile('"+p+"')\">"+n+"</a></span></li>");
		}else{
			pw.println("<li data-options=\"state:'closed'\" >\n<span >"+n+"</span>");
			pw.println("<ul>");
			for(File f:path.listFiles()){
				if(f.isDirectory()){
					rollPath(f,p,pw);
				}
				
			}
			for(File f:path.listFiles()){
				if(f.isFile()){
					rollPath(f,p,pw);
				}
			}
			pw.println("</ul>");
			pw.println("</li>");

		}
	}
	/**
	 * 读取classpath文件
	 * param 
	 * return
	 * description
	 */
	public static String readResource(String classPathFile){
		URL url=Thread.currentThread().getContextClassLoader().getResource(classPathFile);
		try {
			return I2S(url.openStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public static InputStream read(String classPathFile){
		URL url=Thread.currentThread().getContextClassLoader().getResource(classPathFile);
		try {
			return url.openStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	
	public static void dd(){
		String dd="com.huadi.csc.portal/WebRoot/pages/serviceInstance/notice.jsp,com.huadi.csc.portal/WebRoot/js/serviceInstance/serviceInstance.js,com.huadi.csc.persistence/src/com/huadi/csc/persistence/bean/custom/WfResApplyInfo.java,com.huadi.csc.persistence/src/com/huadi/csc/persistence/bean/service/sIntance/ServiceInstance.java,com.huadi.csc.custom/WebRoot/custom/pages/vmApplyInfo/detail_source.jsp,com.huadi.csc.custom/WebRoot/custom/pages/vmApplyInfo/edit_source.jsp,com.huadi.csc.custom/WebRoot/custom/pages/vmApplyInfo/vmApply_sp_detail.jsp,com.huadi.csc.custom/WebRoot/custom/pages/vmmount/vmmount_index4m.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfOrder/wfOrder_index.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfIpApply/wfIpApply_sp_detail.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfResModify/wfResModify_new.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfResModify/wfResModify_detail.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfResModify/wfResModify_submit.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfResModify/wfResModify_sp_detail.jsp,com.huadi.csc.custom/WebRoot/custom/pages/wfResModify/wfResModify_vms.jsp,com.huadi.csc.custom/WebRoot/custom/js/wfHelper.js,com.huadi.csc.custom/WebRoot/custom/js/wfOrder/wfOrder_jg.js,com.huadi.csc.custom/WebRoot/custom/js/wfOrder/wfOrder_noSubimt.js,com.huadi.csc.custom/WebRoot/custom/js/wfOrder/wfOrder_isAudit.js,com.huadi.csc.custom/WebRoot/custom/js/wfOrder/wfOrder_noAudit.js,com.huadi.csc.custom/src/com/huadi/csc/custom/service/WfResModifyService.java,com.huadi.csc.custom/src/com/huadi/csc/custom/service/WfOrderService.java,com.huadi.csc.custom/src/com/huadi/csc/custom/service/WfResApplyInfoService.java,com.huadi.csc.custom/src/com/huadi/csc/custom/service/WfIpApplyService.java,com.huadi.csc.custom/src/com/huadi/csc/custom/task/ResouceModifyTask.java,com.huadi.csc.custom/src/com/huadi/csc/custom/task/ResouceBuildTask.java,com.huadi.csc.sys/src/com/huadi/csc/sys/service/userinfo/emcgnotice/EmcgNoticeService.java";
		String[] d=dd.split(",");
		
		for(String s:d){
			int  ss=s.indexOf("/");
			System.out.format("mFile(\"%s\",\"%s\");\n",s.substring( ss+1), s.substring(0, ss));
		}
	}
	public static void scan(FileInputStream inputStream)throws IOException{
		Scanner sc = null;
		try {
		    sc = new Scanner(inputStream, "UTF-8");
		    int i=1;
		    while (sc.hasNextLine()) {
		        String line = sc.nextLine();
		        System.out.println(i++ + ":\t"+line);
		    }
		    if (sc.ioException() != null) {
		        throw sc.ioException();
		    }
		} finally {
		    if (inputStream != null) {
		        inputStream.close();
		    }
		    if (sc != null) {
		        sc.close();
		    }
		}
	}
	public static void main(String[] as) throws Exception{
		File file=new File("C:\\Users\\lenovo\\Desktop\\MT1101_2017051711433283995_00003.xml");
		scan(new FileInputStream(file));
	
//		BufferedReader bufReader = new BufferedReader(new InputStreamReader(read("1.txt"))); 		
//        
//		Map<String,String> cmds=new HashMap<>();
//		for(String f:p.list()){
//			String ns=f.substring(9,f.lastIndexOf(".")).toLowerCase();
//			String subPkg=null;
//			String name=null;
//			List<String[]> sf=SF.queryArray(ns, "(.*)_(delete|edit|secondly|first).*", 1,2);
//			if(CollectionUtils.isEmpty(sf)){
//				if(ns.endsWith("_2")){
//					subPkg="first";
//				}
//				name=ns.replaceAll("_\\d+", "");
//			}else{
//				name=sf.get(0)[0];
//				subPkg=sf.get(0)[1];
//			}
//			String key=ns.replaceAll("_\\d+", "");
//			//System.out.println(key);
//			cmds.put(key, "call:xsd2java "+f+" "+name+(subPkg==null?"":"."+subPkg)+" y");
//		}
//		String input = null;  
//		while((input=bufReader.readLine())!=null){
//			List<String> dd=SF.query(input, "[\\S]+", 0);
//			if(dd.size()==1){
//				System.out.println("rem ----------------------"+input+"------------------------");
//			}else if(dd.size()==2){
//				
//				String key=dd.get(0);
//				int ii=key.lastIndexOf(".");
//				if(ii>0){
//					key=key.substring(9,ii).toLowerCase();
//				}else{
//					key=key.substring(9).toLowerCase();
//				}
//				
//				if(cmds.containsKey(key)){
//					System.out.println("rem "+dd.get(1));
//					System.out.println(cmds.get(key));
//					cmds.remove(key);
//				}else{
//					System.out.println("rem "+dd.get(1)+"      "+dd.get(0));
//				}
//				
//			}else{
//				//System.out.println("XXXXXXXXXXXX");
//			}
//		}
//		System.out.println("rem ---------------其他-------------------");
//		for(Map.Entry<String, String> cmd:cmds.entrySet()){
//			System.out.println(cmd.getValue());
//		}
	}
	
	public static void randomRead() throws Exception{
		RandomAccessFile raf = new RandomAccessFile("C:\\Users\\lenovo\\Desktop\\log\\log.log", "r");  
		long leng = raf.length();  
		String lastLine = "";  
		long pos=0;
		if(leng >=100000L){
			pos=leng-100001;
			raf.seek(pos);
		}
		byte []buffer=new byte[100];
		  int len=0;
		  while((len=raf.read(buffer, 0, 100))!=-1){
		   System.out.println(new String(buffer,0,len));
		  }
		raf.close();  
		
	}
	
	public static void copyPath(){
		String path="wxcs-yp-ad";
		String outs="E:\\garca\\mission\\qing\\qc\\work\\info.qc.common\\outs"+"\\wxcs-yp-ad";
		String  in=null;
		  in="E:/garca/mission/wonder/eclispe64/workspace/wxcs-yp-ad/src/main/webapp";
		File outp=new File(outs);
		File inf=new File(in,path);
		File outf=new File(outp,inf.getName());
		if(outf.exists()){
			try {
				SFile.clear(outf);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		outf.mkdirs();
		copyFiles(inf, outf);
	}
	
	public static void ddd(){
		 try  
	        {  
			 	String path="C:\\Users\\garca\\Desktop";
				String fn="cc.sql";
				File inf=new File(path,fn);
	            //缓冲System.in输入流  
	            //System.in是位流，可以通过InputStreamReader将其转换为字符流  
	            BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(inf)));  
	            //缓冲FileWriter  
	  
	            String input = null;  
	            int f=100;
	            BufferedWriter bufWriter = new BufferedWriter(new FileWriter(new File(path,"cc"+(f++)+".sql")));  
	            //每读一行进行一次写入动作 
	            int i=0;
	            String sql="";
	            while((input = bufReader.readLine())!=null&&i<50){
	            	sql+=input;
	            	bufWriter.newLine(); 
	            	if(sql.contains(";")){
	            		String utf8 = new String(sql.getBytes( "UTF-8"));  
	            		System.out.println(utf8);  
	            		String unicode = new String(utf8.getBytes(),"unicode");   
	            		System.out.println(unicode);  
	            		String gbk = new String(unicode.getBytes("GBK")); 
	            		System.out.println(gbk);
	            		bufWriter.write(gbk); 
		                sql="";
		                //newLine()方法写入与操作系统相依的换行字符，依执行环境当时的OS来决定该输出那种换行字符  
		                if(i++>=50000){
		                	bufWriter.close();
		                	i=0;
		                	bufWriter= new BufferedWriter(new FileWriter(new File(path,"cc"+(f++)+".sql")));
		            	}
	            	}
	                
	            }  
	            bufWriter.close();
	            bufReader.close();  
	              
	        }  
	        catch(ArrayIndexOutOfBoundsException e)  
	        {  
	            System.out.println("没有指定文件");  
	        }  
	        catch(IOException e)  
	        {  
	            e.printStackTrace();  
	        }
	}
	public static void mkpkg(String pkg){  
		String p=getPathByPkg(pkg);
		String outs="E:\\garca\\mission\\qing\\qc\\work\\info.qc.common\\outs\\";
		createPaths(outs,p);
	}
	public static void openDirectory(File path){  
		if(path instanceof File&&path.isDirectory()){
			 try {  
			        //this will set [d:/aa]  to [d:\\aa]  
			        String cmd = "Explorer.exe " + path.toString();  
//			        String cmd = "Explorer.exe /select," + path.replaceAll("/", "\\\\");
			        Runtime.getRuntime().exec(cmd);  
			    } catch (IOException e) {  
			        e.printStackTrace();  
			    }
		}
	}
	
	public static void readLine(File f) throws Exception{
		//System.in是位流，可以通过InputStreamReader将其转换为字符流  
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); 		
        String input = null;  
		while((input=bufReader.readLine())!=null){
			
		}
	}
	public static void mCl(String cl){
		int ll=cl.lastIndexOf(".");
		String pkg=getPathByPkg(cl.substring(0,ll));
		String name=cl.substring(ll+1)+".class";
		String outs="E:\\garca\\mission\\qing\\qc\\work\\info.qc.common\\outs"+"\\wxcs-yp-ad\\WEB-INF\\classes";
		String  in=null;
		  in="E:/garca/mission/wonder/eclispe64/workspace/wxcs-yp-ad/target/classes";

		String outp=outs+"\\"+pkg;
		String inp=in+"\\"+pkg;
		createPaths(outp);
		File inf=new File(inp,name);
		File outf=new File(outp,name);
		copyFile(inf, outf);
	}
	public static void mPkg(String pkg,String bd){
		String outs="E:\\garca\\mission\\qing\\files\\work\\info.qc.common\\outs\\"+bd;
		String  in="E:\\garca\\mission\\GXCC\\csc88\\work\\"+bd;
		 in="E:\\garca\\mission\\nongshang\\csc44\\work\\"+bd;
		 in="E:\\garca\\mission\\nongshang\\csc89\\works\\"+bd;
		String outp=outs+"\\"+pkg;
		String inp=in+"\\"+pkg;
		createPaths(outp);
		
		File inf=new File(inp);
		File outf=new File(outp);
		copyFiles(inf, outf);
	}
	public static void mFile(String f,String bd){
		int ll=f.lastIndexOf("/");
		String pkg=null;
		String name=null;
		if(ll==-1){
			pkg="";
			name=f;
		}else{
			pkg=f.substring(0,ll);
			name=f.substring(ll+1);
		}
		String outs="E:\\garca\\mission\\qing\\files\\work\\info.qc.common\\outs\\"+bd;
		String  in=null;
		 in="E:\\garca\\mission\\GXCC\\csc88\\work\\"+bd;
		 in="E:\\garca\\mission\\nongshang\\csc89\\works\\"+bd;
		 in="E:\\garca\\mission\\nongshang\\wincenter55\\work\\"+bd;
		 in="E:\\garca\\mission\\nongshang\\csc44\\work\\"+bd;
		String outp=outs+"\\"+pkg;
		String inp=in+"\\"+pkg;
		createPaths(outp);
		File inf=new File(inp,name);
		File outf=new File(outp,name);
		copyFile(inf, outf);
	}
	public static boolean createPaths(String path){
		File file=new File(path);
		return file.mkdirs();
	}
	public static boolean createPaths(String path,String name){
		File file=new File(path,name);
		return file.mkdirs();
	}
	
	public static byte[] readBytes(InputStream in) throws Exception{
		byte[] bytes = new byte[in.available()]; //长度
		in.read(bytes);
		return bytes;
	}
	public static byte[] readBytesNoFlag(byte[] datas,int index,int len) throws Exception{
		return Arrays.copyOfRange(datas, index, index+len-1);
	}
	public static byte[] readBytes4(byte[] datas,int index) throws Exception{
		return readBytesNoFlag(datas, index, 4);
	}
	public static byte[] readBytes2(byte[] datas,int index) throws Exception{
		return readBytesNoFlag(datas, index, 2);
	}
	public static List<String> readByteStr16(InputStream in) throws Exception{
		byte[] bytes = readBytes(in);
		List<String> rs=new ArrayList<String>();
		for(byte b:bytes){
			rs.add(Long.toHexString(b));
		}
		return rs;
	}
	
	
	
	


	/**
	 * 写流
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	public static void write(InputStream in,Writer out) throws IOException{
		int bytesRead;
		char[] buf = new char[4 * 1024]; //4K buffer
		BufferedReader bfi=new BufferedReader(new InputStreamReader(in,DEF_CHARSET));
		while((bytesRead = bfi.read(buf)) != -1){
			out.write(buf, 0, bytesRead);
		}
		out.flush();
		out.close();
	    in.close();
	}
	/**
	 * 写流
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	public static void write(Reader in,Writer out) throws IOException{
		int bytesRead;
		char[] buf = new char[4 * 1024]; //4K buffer
		while((bytesRead = in.read(buf)) != -1){
			out.write(buf, 0, bytesRead);
		}
		out.flush();
		out.close();
	    in.close();
	}
	/**
	 * 写流
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	public static void write(InputStream in,OutputStream out) throws IOException{
		int bytesRead;
		byte[] buf = new byte[4 * 1024]; //4K buffer
		while((bytesRead = in.read(buf)) != -1){
			out.write(buf, 0, bytesRead);
		}
		out.flush();
		out.close();
	    in.close();
	}
	/**
	 * 文件夹复制
	 * @param srcFile
	 * @param desFile
	 * @return
	 */
	public static boolean copyFiles(File srcFile, File desFile){

		if(srcFile.isDirectory()){
			
			if(desFile.isDirectory()){
				for(File f:srcFile.listFiles()){
					if(".svn".equals(f.getName())){
						continue;
					}
					if(f.isFile()){
						copyFile(f, new File(desFile,f.getName()));
					}else if(f.isDirectory()){
						File dFile=new File(desFile,f.getName());
						if(!dFile.exists()){
							createPaths(dFile.getAbsolutePath());
						}
						copyFiles(f,dFile );
					}
					
				}
			}else{
				SD.debug(desFile.getAbsolutePath()+" is not a fold");
				return false;
			}
			
		}else{
			SD.debug(srcFile.getAbsolutePath()+" is not a fold");
			return false;
		}
    	
    	return true;
    }
	/**
	 * 文件复制
	 * @param srcFile
	 * @param desFile
	 * @return
	 */
	public static boolean copyFile(File srcFile, File desFile){
    	checkPossibleFile(desFile);
    	checkFile(srcFile);
    	FileInputStream fis = null;
    	FileOutputStream fos = null;
    	try{
    		desFile.createNewFile();
    		fis = new FileInputStream(srcFile);
    		fos = new FileOutputStream(desFile);
    		int bytesRead;
    		byte[] buf = new byte[4 * 1024]; //4K buffer
    		while((bytesRead = fis.read(buf)) != -1){
    			fos.write(buf, 0, bytesRead);
    		}
    	    fos.flush();
    	    fos.close();
    	    fis.close();
    	}catch(IOException e){
    		e.printStackTrace();
    	    return false;
    	}
    	return true;
    }
	/**
	 * 检查文件是否可行
	 * @param file
	 * @return
	 */
	public static boolean checkPossibleFile(File file){
    	if(file==null){
    		throw new RuntimeException("文件为null");
		}
    	if(!file.getParentFile().exists()){
			throw new RuntimeException("文件路径不存在:"+file.getParentFile().getPath());
		}
		return true;
    }
	/**
	 * 检查文件
	 * @param file
	 * @return
	 */
    public static boolean checkFile(File file){
    	checkPossibleFile(file);
    	if(!file.isFile()){
			throw new RuntimeException("文件不存在:"+file.getAbsolutePath());
		}
		return true;
    }
	
	
	
	/**
	 * 流转化为字符串
	 * @param in
	 * @return
	 */
	public static String I2S(InputStream in){
		StringWriter wt=new StringWriter();
		try {
			write(in, wt);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return wt.getBuffer().toString();
	}
	public static InputStream S2I(String str){
		return new ByteArrayInputStream(str.getBytes());
	}
	public static Reader S2R(String str){
		return new StringReader(str);
	}
	public static Reader I2R(InputStream in){
		return new InputStreamReader(in);
	}
	public static Writer O2W(OutputStream out){
		return new OutputStreamWriter(out);
	}
	public static String getPathByPkg(String pkg){
		return pkg.replaceAll("\\.", "\\\\");
	}
	/**
	 * 清理文件夹内部所有文件
	 * @param f
	 * @return
	 */
	public static void clear(File p)throws Exception{
		if(!p.exists()){
			return;
		}
		File[] fs=p.listFiles();
		for(int i=fs.length-1;i>=0;i--){
			File f=fs[i];
			if(f.isDirectory()){
				clear(f);
			}else{
			}
			rmFile(f);
		}
	}
	/**
	 * 删除文件夹或文件
	 * @param f
	 * @return
	 */
	public static void rm(File f)throws Exception{
		if(f==null){
			throw new IOException("文件不能为null");
		}
		if(f.exists()){
			
		}else{
			throw new IOException("文件不存在"+f.getAbsolutePath());
		}
		if(f.isDirectory()){
			rmDir(f);
		}else{
			rmFile(f);
		}
	}
	/**
	 * 删除文件
	 * @param f
	 * @return
	 */
	public static void rmFile(File f)throws Exception{
		if(!f.delete()){
			throw new IOException("文件删除失败:"+f.getAbsolutePath());
		}
	}
	/**
	 * 删除文件夹
	 * @param f
	 * @return
	 */
	public static void rmDir(File f)throws Exception{
		clear(f);
		rmFile(f);
	}
	public static void appendPath(File path0,File path) throws Exception{
        for(File row:path0.listFiles()){
        	String name=row.getName();
        	File file=new File(path,name);
        	FileChannel out = new RandomAccessFile(file,"rw").getChannel();
        	if(out.size()>0){
        		out.position(out.size());
            	out.write(ByteBuffer.wrap(System.getProperty("line.separator").getBytes()));
        	}
        	FileChannel in=new FileInputStream(row).getChannel();
        	out.transferFrom(in, out.size(), in.size());
        	in.close();
        	out.close();
        }
	}
	public static void append(File inFile,File outFile) throws Exception{
        	FileChannel out = new RandomAccessFile(outFile,"rw").getChannel();
        	if(out.size()>0){
        		out.position(out.size());
            	out.write(ByteBuffer.wrap(System.getProperty("line.separator").getBytes()));
        	}
        	FileChannel in=new FileInputStream(inFile).getChannel();
        	out.transferFrom(in, out.size(), in.size());
        	in.close();
        	out.close();
	}    	
}
